﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Npgsql;
using System.Diagnostics;
using System.IO;

namespace SpeedTestServerSetup
{
	public partial class Page2 : WizardPage
	{
        public override event StateChangeEvent ReadyStateChanged;

        public Page2()
		{
			InitializeComponent();
		}

        public override void LeavePage(WizardEvents e)
		{
			//only validate if moving to the next page
			if (e.Direction != WizardDirection.Next) { return; }	

            //try to connect to the database. If not, return cancel and prompt user
			if (IsPageReady())
			{
				if (!AttemptConnect())
				{
					MessageBox.Show(this, "Unable to connect to the specified database. Please verify your entries in the Server Details section.", "Error");
					e.Cancel = true;
				}

                ConfigurationManager.AppSettings.Set("PGServerName", txtServerName.Text);
				ConfigurationManager.AppSettings.Set("PGPort", txtPort.Text);
				ConfigurationManager.AppSettings.Set("PGUserName", txtUserName.Text);
                ConfigurationManager.AppSettings.Set("PGPassword", txtPassword.Text);
			}
		}

        private bool AttemptConnect()
        {
            Data data = new Data(txtServerName.Text, txtPort.Text, 
				txtUserName.Text, txtPassword.Text);

            return data.Connect();
        }

        public override void EnterPage(WizardEvents e)
		{
			if (IsPageReady() && ReadyStateChanged != null) { ReadyStateChanged.Invoke(IsPageReady()); }
		}

        private bool IsPageReady()
        {
            if (String.IsNullOrEmpty(txtServerName.Text)) { return false; } 
            if (String.IsNullOrEmpty(txtPort.Text)) { return false; }
            if (String.IsNullOrEmpty(txtUserName.Text)) { return false; }
            if (String.IsNullOrEmpty(txtPassword.Text)) {return false; }

            return true;
        }

        private void RequiredInput_TextChanged(object sender, EventArgs e)
        {
            if(ReadyStateChanged != null) { ReadyStateChanged.Invoke(IsPageReady()); }
        }

        private void txtPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            int parsedNumber = 0;
            e.Handled = !Int32.TryParse(e.KeyChar.ToString(), out parsedNumber);
			if (e.KeyChar == (char)Keys.Delete || e.KeyChar == (char)Keys.Back) { e.Handled = false; }
        }

		private void linkDownload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Process.Start("http://www.enterprisedb.com/products/pgdownload.do");
		}


	}
}
